﻿using System;
using System.Linq;
using System.Text;
using System.Web;

namespace FBGraph.Web.Security
{
    /// <summary>An implementation of <see cref="FBGraphHttpHandler" /> that handles the callback from Facebook during an authorization request.</summary>
    public class FBGraphPostAuthorizeRequestHandler : FBGraphHttpHandler
    {
        internal const String PATH = "POSTAUTHORIZE";

        /// <summary>Reads the authorization data from Facebook and attempts to request an OAuth 2.0 access token.</summary>
        protected override void ProcessRequest()
        {
            var idSegment = Request.Url.Segments.Last();
            var id = default(Guid);

            try { id = new Guid(idSegment); }
            catch (Exception ex) { throw new ArgumentException("Error parsing request id", "id", ex); }

            var code = Request.QueryString["code"];
            if (String.IsNullOrEmpty(code)) throw new ArgumentException("code is missing or empty", "code");

            AuthRequestData requestData;
            if (this.FbContext.ProcessAuthenticationCallback(code, id, out requestData)) this.Response.Redirect(requestData.ReturnUrl);
            else
            {
                var redirect = new StringBuilder(this.AuthUrl);
                redirect.Append("authorize");
                redirect.AppendFormat("?scope={0}&returnUrl={1}", requestData.Scope, requestData.ReturnUrl);
                this.Response.Redirect(redirect.ToString());
            }

        }
    }
}